package com.bree.erp.jsf.datatable;

import java.util.Comparator;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.log4j.Logger;
import org.primefaces.model.SortOrder;

public class LazySorter<T> implements Comparator<T> {

	private static Logger LOG = Logger.getLogger(LazySorter.class);

	private String sortField;

	private SortOrder sortOrder;

	private PropertyUtilsBean utilsBean;

	public LazySorter(String sortField, SortOrder sortOrder) {
		this.sortField = sortField;
		this.sortOrder = sortOrder;

		utilsBean = new PropertyUtilsBean();
	}

	@Override
	public int compare(T o1, T o2) {

		Object value1 = "";
		Object value2 = "";
		boolean cont = true;
		try {
			value1 = utilsBean.getProperty(o1, this.sortField);
		} catch (Exception e) {
			value1 = "B"; 
			value2 = "A";
			cont = false;
		}

		if (cont) {
			try {
				value2 = utilsBean.getProperty(o2, this.sortField);
			} catch (Exception e) {
				value1 = "A"; 
				value2 = "B";
			}
		}

		try {

			int value = ((Comparable) value1).compareTo(value2);

			return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			throw new RuntimeException();
		}
	}

}
